/*
 * Copyright (c) 2013 Joakim Lindskog
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.limewoodmedia.nsdroid.activities;

import static com.limewoodMedia.nsapi.holders.RegionData.Shards.*;

import java.io.IOException;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.limewoodMedia.nsapi.exceptions.RateLimitReachedException;
import com.limewoodMedia.nsapi.exceptions.UnknownRegionException;
import com.limewoodMedia.nsapi.holders.RegionData;
import com.limewoodmedia.nsdroid.R;
import com.limewoodmedia.nsdroid.API;
import com.limewoodmedia.nsdroid.LoadingHelper;
import com.limewoodmedia.nsdroid.TagParser;
import com.limewoodmedia.nsdroid.holders.RegionDataParcelable;
import com.limewoodmedia.nsdroid.views.LoadingView;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Region extends SherlockFragmentActivity {
	public static final String TAG = Region.class.getName();

	private ViewGroup layout;
	private TextView regionName;
	private ImageView flag;
	private TextView delegate;
	private TextView founder;
	private TextView wfe;
	private ViewGroup fieldset;
	private TextView header;
	
	private String region;
	private RegionDataParcelable data;
	private String errorMessage;
	private boolean homeRegion = false;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
        setContentView(R.layout.region);

        // Fetch flag
        LoadingHelper.loadHomeFlag(this);
        
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        
        layout = (ViewGroup) findViewById(R.id.region_layout);
        regionName = (TextView) findViewById(R.id.region_name);
        flag = (ImageView) findViewById(R.id.region_flag);
        delegate = (TextView) findViewById(R.id.region_delegate);
        founder = (TextView) findViewById(R.id.region_founder);
        wfe = (TextView) findViewById(R.id.wfe);
        delegate.setMovementMethod(LinkMovementMethod.getInstance());
        founder.setMovementMethod(LinkMovementMethod.getInstance());
        wfe.setMovementMethod(LinkMovementMethod.getInstance());
        fieldset = (ViewGroup) findViewById(R.id.fieldset);
        header = (TextView) findViewById(R.id.wfe_header);
        ViewTreeObserver observer = header.getViewTreeObserver();
		observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
		    @Override
		    public void onGlobalLayout() {
		    	fieldset.setPadding(fieldset.getPaddingLeft(), header.getHeight() -
						(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15,
							getResources().getDisplayMetrics()), fieldset.getPaddingRight(),
							fieldset.getPaddingBottom());
		    }
		});
        
        Log.d(TAG, "DATA "+getIntent().getDataString());
        if(getIntent().getData() == null) {
        	// Get user's region
        	homeRegion = true;
        }
        else {
        	region = getIntent().getDataString().replace("com.limewoodMedia.nsdroid.region://", "");
        }
        
        if(savedInstanceState == null) {
	    	loadRegion();
        } else {
        	// Restore state
        	data = savedInstanceState.getParcelable("region_data");
        	doSetup();
        }
    }
    
    private void loadRegion() {
    	layout.setVisibility(View.GONE);
    	final LoadingView loadingView = (LoadingView) findViewById(R.id.loading);
    	LoadingHelper.startLoading(loadingView, R.string.loading_region, this);
    	errorMessage = getResources().getString(R.string.general_error);
        new AsyncTask<Void, Void, Boolean>() {
        	protected Boolean doInBackground(Void...params) {
				try {
					RegionData.Shards[] shards = new RegionData.Shards[]{
							NAME, FACTBOOK, DELEGATE, FOUNDER, FLAG
					};
					if(homeRegion) {
						data = API.getInstance(Region.this).getHomeRegionInfo(Region.this, shards);
						region = data.name;
					} else {
						data = API.getInstance(Region.this).getRegionInfo(region, shards);
					}
	                
            		data.flagBitmap = LoadingHelper.loadFlag(data.flagURL, Region.this);
	                return true;
				} catch (RateLimitReachedException e) {
					e.printStackTrace();
					errorMessage = getResources().getString(R.string.rate_limit_reached);
				} catch (UnknownRegionException e) {
					e.printStackTrace();
					errorMessage = getResources().getString(R.string.unknown_region);
				} catch (RuntimeException e) {
					e.printStackTrace();
					errorMessage = e.getMessage();
				} catch (IOException e) {
					e.printStackTrace();
					errorMessage = e.getMessage();
				}
				
				return false;
        	};
        	
        	protected void onPostExecute(Boolean result) {
        		LoadingHelper.stopLoading(loadingView);
        		if(result) {
        			doSetup();
        		}
        		else {
        			Toast.makeText(Region.this, errorMessage, Toast.LENGTH_SHORT).show();
        		}
        	};
        }.execute();
    }
    
    private void doSetup() {
    	// Region name
		setTitle(data.name);
		regionName.setText(data.name);
		// Flag
		if(data.flagBitmap != null) {
			flag.setImageBitmap(data.flagBitmap);
		} else {
			flag.setVisibility(View.GONE);
		}
		// WA Delegate
		StyleSpan bold = new StyleSpan(android.graphics.Typeface.BOLD);
		String wadTitle = getResources().getString(R.string.wad);
		String wad = TagParser.idToName(data.delegate);
		if(!wad.equals("0")) {
    		wad = wadTitle+" <a href=\"com.limewoodMedia.nsdroid.nation://"+wad+"\">"+wad+"</a>";
    		delegate.setText(Html.fromHtml(wad), TextView.BufferType.SPANNABLE);
		} else {
			delegate.setText(wadTitle + " " + getResources().getString(R.string.no_wad));
		}
		((Spannable)delegate.getText()).setSpan(bold, 0, wadTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		// Founder
		String found = TagParser.idToName(data.founder);
		if(!found.equals("0")) {
    		String fTitle = getResources().getString(R.string.founder);
    		found = fTitle+" <a href=\"com.limewoodMedia.nsdroid.nation://"+found+"\">"+found+"</a>";
    		founder.setText(Html.fromHtml(found), TextView.BufferType.SPANNABLE);
    		((Spannable)founder.getText()).setSpan(bold, 0, fTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    		founder.setVisibility(View.VISIBLE);
		} else {
			founder.setVisibility(View.GONE);
		}
		wfe.setText(TagParser.parseTagsFromHtml(data.factbook));
        layout.setVisibility(View.VISIBLE);
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	
    	outState.putParcelable("region_data", data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.menu_region, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case android.R.id.home: {
	        	Intent i = new Intent(this, NSDroid.class);
	        	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        	startActivity(i);
	        	break;
	        }
            case R.id.menu_nation: {
            	Intent i = new Intent(this, Nation.class);
            	startActivity(i);
            	break;
            }
	        case R.id.menu_region: {
	        	Intent i = new Intent(this, Region.class);
	        	startActivity(i);
	        	break;
	        }
            case R.id.menu_rmb: {
            	Intent i = new Intent(this, RMB.class);
            	i.setData(Uri.parse("com.limewoodMedia.nsdroid.region.rmb://"+region));
            	startActivity(i);
            	break;
            }
            case R.id.menu_embassies: {
            	Intent i = new Intent(this, Embassies.class);
            	i.setData(Uri.parse("com.limewoodMedia.nsdroid.region.embassies://"+region));
            	startActivity(i);
            	break;
            }
	        case R.id.menu_add_region_to_dossier:
	        	new AsyncTask<Void, Void, Void>() {
	        		@Override
	        		protected Void doInBackground(Void... params) {
	    	        	if(API.getInstance(Region.this).checkLogin(Region.this)) {
	    	        		try {
	    						if(API.getInstance(Region.this).addRegionToDossier(region.replace(' ', '_').toLowerCase())) {
	    							runOnUiThread(new Runnable() {
	    								public void run() {
	    	    							Toast.makeText(Region.this, R.string.region_added_to_dossier, Toast.LENGTH_SHORT).show();
	    								};
	    							});
	    						}
	    					} catch (IOException e) {
	    						e.printStackTrace();
	    					}
	    	        	}
	        			return null;
	        		}
	        	}.execute();
	        	break;
            case R.id.menu_refresh:
            	loadRegion();
            	break;
            case R.id.menu_settings: {
            	Intent i = new Intent(this, Preferences.class);
            	startActivity(i);
            	break;
            }
        }
        return super.onOptionsItemSelected(item);
    }
}
